"""
统一异常处理
"""
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
from typing import Optional
import logging
import traceback
from app.schemas.response import ApiResponse

logger = logging.getLogger(__name__)

class AppException(Exception):
    """应用基础异常类"""
    def __init__(self, message: str, status_code: int = 500, error_code: Optional[str] = None):
        self.message = message
        self.status_code = status_code
        self.error_code = error_code
        super().__init__(self.message)

class AuthenticationException(AppException):
    """认证异常"""
    def __init__(self, message: str = "认证失败"):
        super().__init__(message, 401, "AUTH_ERROR")

class AuthorizationException(AppException):
    """授权异常"""
    def __init__(self, message: str = "权限不足"):
        super().__init__(message, 403, "AUTHORIZATION_ERROR")

class NotFoundException(AppException):
    """资源未找到异常"""
    def __init__(self, message: str = "资源未找到"):
        super().__init__(message, 404, "NOT_FOUND")

class ValidationException(AppException):
    """数据验证异常"""
    def __init__(self, message: str = "数据验证失败"):
        super().__init__(message, 400, "VALIDATION_ERROR")

async def app_exception_handler(request: Request, exc: AppException):
    """应用异常处理器"""
    logger.error(f"应用异常: {exc.message}", exc_info=True)
    
    return JSONResponse(
        status_code=exc.status_code,
        content=ApiResponse(
            success=False,
            message=exc.message,
            error={
                "code": exc.error_code,
                "message": exc.message
            }
        ).dict()
    )

async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理器"""
    logger.warning(f"HTTP异常: {exc.detail}", exc_info=True)
    
    return JSONResponse(
        status_code=exc.status_code,
        content=ApiResponse(
            success=False,
            message=exc.detail,
            error={
                "code": "HTTP_ERROR",
                "message": exc.detail
            }
        ).dict()
    )

async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理器"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    
    return JSONResponse(
        status_code=500,
        content=ApiResponse(
            success=False,
            message="服务器内部错误",
            error={
                "code": "INTERNAL_ERROR",
                "message": "服务器内部错误"
            }
        ).dict()
    )